import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2022-12-18
 * Time:14:35
 */
@WebServlet("/blog_delete")
public class BLogDelete extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、先判定用户的登录状态
        HttpSession session =  req.getSession(false);
        if(session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html ;charset=utf8");
            resp.getWriter().write("您当前未登录不能删除");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html ;charset=utf8");
            resp.getWriter().write("您当前未登录不能删除");
            return;
        }
        //2、获取到blogId
        String blogId = req.getParameter("blogId");
        if(blogId == null) {
            //这个blogId参数不存在，无法删除
            resp.setStatus(404);
            resp.setContentType("text/html ;charset=utf8");
            resp.getWriter().write("您当前要删除的blogId有误，不能删除");
            return;
        }
        //3、查询出这个BlogId对应的Blog对象
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        if(blog == null) {
            //blogId不存在,无法删除
            resp.setStatus(404);
            resp.setContentType("text/html ;charset=utf8");
            resp.getWriter().write("当前博客不存在 blogId = " + blogId);
            return;
        }
        //4、判定登录用户是否就是文章作者
        if(blog.getBlogId() != user.getUserId()) {
            //非作者
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("您不能删除别人的博客");
            return;
        }
        //5、真正执行删除
        blogDao.delete(Integer.parseInt(blogId));
        //6、返回302
        resp.sendRedirect("blog_list.html");
    }
}
